package com.ckx.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.ckx.domain.ResponseResult;
import com.ckx.enums.AppHttpCodeEnum;
import com.ckx.exception.SystemException;
import com.ckx.service.UploadService;
import com.ckx.utils.PathUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;

@Service
public class UploadServiceImpl implements UploadService {

    @Value("${spring.cloud.alicloud.access-key}")
    private String accessKeyId;
    @Value("${spring.cloud.alicloud.secret-key}")
    private String secretAccessKey;
    @Value("${spring.cloud.alicloud.oss.endpoint}")
    private String endPoint;
    @Value("${spring.cloud.alicloud.oss.bucket}")
    private String bucket;
    @Value("${spring.cloud.alicloud.prefix}")
    private String prefix;

    @Override
    public String uploadImg(MultipartFile img) throws IOException {

        if (Objects.isNull(img)){
            throw new SystemException(AppHttpCodeEnum.ARGS_FAIL);
        }
        //判断文件类型 (要求为 图片格式)
        String originalFilename = img.getOriginalFilename();
        if (!originalFilename.endsWith(".png") && !originalFilename.endsWith(".jpg")){
            throw new SystemException(AppHttpCodeEnum.FILE_TYPE_ERROR);
        }
        //上传文件到阿里云
        InputStream inputStream = img.getInputStream();
        String url = upload2Oss(inputStream, originalFilename);

        return url;
    }

    //返回 文件访问路径
    private String upload2Oss(InputStream inputStream, String fileName) throws IOException {

        //创建 OSSClient 实例。
        OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId,
                secretAccessKey);
        //设置文件上传路径
        String path = PathUtils.getYearMonthDay() + fileName;
        //上传文件
        ossClient.putObject(bucket, path, inputStream);
        //关闭 OSSClient。
        ossClient.shutdown();

        return prefix + path;
    }

}
